package integraltask

import (
	"context"
	"fmt"
	"strings"

	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/types/setting"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetIntegralTaskListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetIntegralTaskListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetIntegralTaskListLogic {
	return &GetIntegralTaskListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetIntegralTaskListLogic) GetIntegralTaskList(in *setting.IntegralTaskListReq) (*setting.IntegralTaskListResp, error) {
	logx.Infof("GetIntegralTaskList : %+v ", in)
	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)

	logrus.Info(fmt.Sprintf("GetIntegralTaskList preloadMap: %+v", preloadMap))

	logrus.Info(fmt.Sprintf("GetIntegralTaskList eagerLoadMap: %+v", eagerLoadMap))

	settingIntegralTaskEntityName := model.RpcEntityNames.IntegralTask
	_, hasSettingMap := model.RpcEntityPreloadMap[settingIntegralTaskEntityName]
	if !hasSettingMap {
		return &setting.IntegralTaskListResp{}, nil
	}

	settingIntegralTaskRepositoryName := model.RepositoryNames.IntegralTask
	columnMap, hasColumnMap := model.RepositoryPreloadMap[settingIntegralTaskRepositoryName]
	if !hasColumnMap {
		return &setting.IntegralTaskListResp{}, nil
	}

	var selectCols []string
	if preloadFields, hasPreloadFields := preloadMap[settingIntegralTaskEntityName]; hasPreloadFields {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	logrus.Info(fmt.Sprintf("GetIntegralTaskList filterMap: %+v", filterMap))
	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	logrus.Info(fmt.Sprintf("GetIntegralTaskList orderBy: %s", orderBy))
	if len(orderBy) == 0 {
		orderBy = model.SysUserIntegralTaskColumns.UpdatedAt + " DESC"
	}

	res, count, err := l.svcCtx.IntegralTask.GetList(l.ctx, model.M{
		"offset": in.Offset,
		"limit":  in.Limit,
		// "search":  in.Search,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, 2, filterMap)
	if err != nil {
		return nil, err
	}

	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &setting.IntegralTaskListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}

	if len(res) > 0 {
		for _, v := range res {
			resp.List = append(resp.List, &setting.IntegralTaskInfo{
				Id:            pointy.GetPointer(v.ID),
				RuleName:      pointy.GetPointer(v.RuleName),
				RuleSlug:      pointy.GetPointer(v.RuleSlug),
				RuleType:      pointy.GetPointer(uint32(v.RuleType)),
				PicId:         pointy.GetPointer(v.PicID),
				PicUrl:        pointy.GetPointer(v.PicURL),
				Frequency:     pointy.GetPointer(uint32(v.Frequency)),
				Points:        pointy.GetPointer(v.Points),
				EffectiveTime: pointy.GetPointer(modelx.FormatTime(v.EffectiveTime, "")),
				Ip:            pointy.GetPointer(v.IP),
				Description:   pointy.GetPointer(modelx.FormatNullDotString(v.Description)),
				Sort:          pointy.GetPointer(uint32(v.Sort)),
				Status:        pointy.GetPointer(uint32(v.Status)),
				CreatedAt:     pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:     pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
				DeletedAt:     pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
			})
		}
	}
	resp.Total = uint64(len(resp.List))

	return resp, nil
}
